package com.jihu.rpc.server.manager;

import com.huge.rpc.Request;
import com.huge.rpc.ServiceDescriptor;
import com.huge.rpc.common.utils.ReflectionUtils;
import com.jihu.rpc.server.instance.ServiceInstance;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 管理RPC暴露的服务
 * @author jihu
 * @date 2020/10/13
 */
@Slf4j
public class ServiceManager {
    private Map<ServiceDescriptor, ServiceInstance> services;

    public ServiceManager(){
        this.services = new ConcurrentHashMap<>();
    }

    public <T> void register(Class<T> interfaceClass , T bean){
        Method[] methods = ReflectionUtils.getPublicMethods(interfaceClass);
        ServiceInstance serviceInstance = null;
        ServiceDescriptor serviceDescriptor = null;
        for (Method method : methods) {
            serviceInstance = new ServiceInstance(bean, method);
            serviceDescriptor = ServiceDescriptor.from(interfaceClass, method);

            services.put(serviceDescriptor,serviceInstance);
            log.info("register service: {} {}",serviceDescriptor.getClazz(),serviceDescriptor.getMethod());
        }
    }

    public ServiceInstance lookup(Request request){
        ServiceDescriptor serviceDescriptor = request.getService();
        return services.get(serviceDescriptor);
    }

}
